use std::{
    fs,
    path::{Path, PathBuf},
};

/// TS 文件的标识数据
const TS_TAG: [u8; 25] = [
    0, 1, 252, 128, 20, 72, 18, 1, 6, 70, 70, 109, 112, 101, 103, 9, 83, 101, 114, 118, 105, 99,
    101, 48, 49,
];

/// 识别ts文件
#[test]
fn test1() {
    let dir = Path::new("/home/jaakan/下载/7_tmp/");
    let dir_read = fs::read_dir(dir.to_path_buf()).unwrap();

    let file_list = dir_read
        .filter(|f| f.is_ok())
        .filter(|f| {
            f.as_ref()
                .unwrap()
                .file_name()
                .clone()
                .to_str()
                .unwrap()
                .ends_with(".ts")
        })
        .map(|f| f.unwrap())
        .map(|f| f.path())
        .collect::<Vec<_>>();

    for f in file_list {
        let _f = f.clone();
        let f_name = _f.file_name().unwrap();
        let data = fs::read(f).unwrap();
        let head_data = &data[0..128];
        let ver = verify_ts(&head_data);
        if !ver {
            println!("文件{:?}非ts文件,文件大小:{}", f_name, data.len());
        }

        if data.len() > 1024 && !verify_ts(&head_data) {
            println!("文件{:?}不是TS 文件》》》》》》》》》", f_name);
        }
    }
}

#[test]
fn test4() {
    let data = include_bytes!("/home/jaakan/下载/7_tmp/9.ts");
    let _data = &data[0..128];
    println!("{:?}", _data);
    println!("is ts file: {:?}", verify_ts(_data));
}

fn verify_ts(data: &[u8]) -> bool {
    if data.len() <= TS_TAG.len() {
        return false;
    }

    let mut s_index = 0;
    for (i, c) in data.iter().enumerate() {
        // 首字母匹配
        if &TS_TAG[s_index] == c {
            s_index += 1;
            if s_index == TS_TAG.len() {
                return true;
            }
        } else {
            s_index = 0;
        }
    }
    return false;
}

#[test]
fn test3() {
    let v_data = [
        0, 1, 252, 128, 20, 72, 18, 1, 6, 70, 70, 109, 112, 101, 103, 9, 83, 101, 114, 118, 105,
        99, 101, 48, 49, 119, 124, 67, 202, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
        255, 255, 255, 255, 255, 255, 255, 255,
    ];
    let data = [
        0, 1, 252, 128, 20, 72, 18, 1, 6, 70, 70, 109, 112, 101, 103, 9, 83, 12, 114, 118, 105, 99,
        101, 48, 49, 167, 121, 160, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
        255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
        255, 255, 255, 255, 255,
    ];

    for i in 0..64 {
        if v_data[i] == data[i] {
            print!("{},", v_data[i]);
            continue;
        }
        break;
    }
    println!("-------");

    println!(
        "{}",
        [
            0, 1, 252, 128, 20, 72, 18, 1, 6, 70, 70, 109, 112, 101, 103, 9, 83, 101, 114, 118,
            105, 99, 101, 48, 49
        ]
        .len()
    );

    println!("{}", verify_ts(&data));
    println!("{}", verify_ts(&v_data));
}
